package org.gpp.proj1.logic.shop.list;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.gpp.proj1.logic.metadata.PartCategory;
import org.gpp.proj1.logic.metadata.PartEntry;
import org.gpp.proj1.robot.part.SparePart;
import org.gpp.proj1.robot.part.parser.InvalidPartFileException;
import org.gpp.proj1.robot.part.parser.PartFileParser;

import com.jme.util.LoggingSystem;

/**
 * @author Paolo Victor, paolovictor@gmail.com
 */
public class PartListLoader {

	public static final String DEFAULT_PARTS_LIST = "res/part/parts.list";

	/**
	 * @param partsListFile The part list file. Format:
	 * 
	 * <number of parts>
	 * for <number of parts lines>
	 *   <part category> <part file path>
	 * 
	 * @return
	 * @throws FileNotFoundException 
	 * @throws InvalidPartFileException 
	 */
	public static Map<PartCategory, Map<String, PartEntry>> loadParts(String partsListFile) throws FileNotFoundException {
		if( partsListFile == null ) {
			throw new IllegalArgumentException( "null file name" );
		}
		
		Map<PartCategory, Map<String, PartEntry>> partsMap = new HashMap<PartCategory, Map<String, PartEntry>>();
		
		File file = new File( partsListFile );
		Scanner scanner = new Scanner( file );
		
		while( scanner.hasNextLine() ) {
			String partDefinition = scanner.nextLine();
			
			if( partDefinition != null &&
				! partDefinition.equals("") ) {
				String[] params = partDefinition.split( " +" );
				
				if( params.length != 2 ) {
					continue;
				}
				
				String category = params[0];
				String filename = params[1];
				
				SparePart part = null;
				try {
					part = PartFileParser.parseFile( filename );
				} catch (InvalidPartFileException e) {
					LoggingSystem.getLogger().warning( "Can't load part file: \"" + filename + "\"" );
					LoggingSystem.getLogger().throwing( "PartListLoader", "loadParts", e );
					
					continue;
				}
				
				if( ! partsMap.containsKey( PartCategory.valueOf( category.toUpperCase() ) ) ) {
					partsMap.put( PartCategory.valueOf( category.toUpperCase() ), new HashMap<String, PartEntry>() );
				}
				
				partsMap.get( PartCategory.valueOf( category.toUpperCase() ) ).put( part.getName(), new PartEntry( part, filename ) );
			}
		}
		
		return partsMap;
	}

}
